package com.itheima.controller;

import com.itheima.bean.Book;
import com.itheima.common.R;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    /**
     * 查询所有书籍信息的方法
     */
    @GetMapping
    public R getAll() {
        List<Book> list = bookService.getAll();
        if (list.size() > 0) {
            return new R(10011,list,"请求成功");
        }
        return new R(10010,"","请求失败,请检查检索条件");
    }

    /**
     * 添加书籍信息
     */
    @PostMapping
    public R save(@RequestBody Book book) {
        System.out.println(book);
        boolean flag = bookService.save(book);
        if (flag) {
            return new R(20011,"","添加成功");
        }
        return new R(20010,"","添加失败");
    }
    /**
     * 根据id 删除书籍信息
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        if (flag) {
            return new R(20021,"","删除成功");
        }
        return new R(20020,"","删除失败");

    }
    /**
     * 根据id 查询
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        if (book == null) {
            return new R(20040, "", "查询的数据不存在,请重新操作");

        }
        return new R(20041,book,"查询成功");
    }

    /**
     * 修改书籍信息
     * @param book
     * @return
     */
    @PutMapping
    public R update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        if (flag) {
            return new R(20031,"","修改成功");
        }
        return new R(20030,"","修改失败");
    }
}
